package com.lecyon.farm.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.lecyon.farm.base.BaseResponse;
import com.lecyon.farm.common.constant.CommonConstant;
import com.lecyon.farm.common.constant.FarmSysConstant;
import com.lecyon.farm.common.exception.FarmException;
import com.lecyon.farm.entity.FmCoop;
import com.lecyon.farm.entity.JsSysOffice;
import com.lecyon.farm.mapper.FmCoopMapper;
import com.lecyon.farm.service.IFmCoopService;
import com.lecyon.farm.service.IJsSysOfficeService;
import com.lecyon.farm.util.RedisUtils;
import com.lecyon.farm.util.ResultUtil;
import com.lecyon.farm.vo.view.StatisticFmCoopVo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Set;

/**
 * 合作社信息表 服务实现类
 *
 * @author YaoZheng
 * @since 2020-04-02
 */
@Service
@Validated
public class FmCoopServiceImpl extends ServiceImpl<FmCoopMapper, FmCoop> implements IFmCoopService {

    private static final Logger LOG = LoggerFactory.getLogger(FmCoopServiceImpl.class);

    private IJsSysOfficeService jsSysOfficeService;

    private FmCoopMapper mapper;

    private RedisUtils redisUtils;

    /**
     * 按区域统计合作社数量
     *
     * @return
     */
    @PostConstruct
    @Scheduled(fixedRate = FarmSysConstant.SCHEDULE_FIX_RATE_PER_DAY)
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse statisticCoopByArea() {
        List<StatisticFmCoopVo> areaResultList = Lists.newLinkedList();
        boolean redisFlag;
        String itemKey;
        String key = FarmSysConstant.REDIS_KEY_STATISTIC_COOPERATION;
        List<JsSysOffice> jsSysOfficeList = jsSysOfficeService.getAll();
        List<JsSysOffice> treeJsSysOfficeList;
        String officeCode;
        Set<String> officeCodeSet = Sets.newHashSet();
        QueryWrapper<FmCoop> fmCoopQueryWrapper;
        QueryWrapper<JsSysOffice> jsSysOfficeQueryWrapper;
        int count;
        if (CollectionUtils.isNotEmpty(jsSysOfficeList)) {
            for (JsSysOffice jsSysOffice : jsSysOfficeList) {
                officeCodeSet.clear();
                areaResultList.clear();
                itemKey = jsSysOffice.getOfficeCode();
                officeCode = jsSysOffice.getOfficeCode();
                officeCodeSet.add(officeCode);
                jsSysOfficeQueryWrapper = new QueryWrapper<>();
                fmCoopQueryWrapper = new QueryWrapper<>();
                jsSysOfficeQueryWrapper.like("parent_codes", officeCode);
                treeJsSysOfficeList = jsSysOfficeService.list(jsSysOfficeQueryWrapper);
                if (CollectionUtils.isNotEmpty(treeJsSysOfficeList)) {
                    for (JsSysOffice treeJsSysOffice : treeJsSysOfficeList) {
                        officeCodeSet.add(treeJsSysOffice.getOfficeCode());
                    }
                }
                fmCoopQueryWrapper.in("location", officeCodeSet);
                count = count(fmCoopQueryWrapper);
                if (0 == count) {
                    // 数量为0 跳过
                    continue;
                }
                StatisticFmCoopVo statisticFmCoopVo = new StatisticFmCoopVo();
                statisticFmCoopVo.setLocation(officeCode);
                statisticFmCoopVo.setLocationName(jsSysOffice.getOfficeName());
                statisticFmCoopVo.setParentAreaCode(jsSysOffice.getParentCode());
                statisticFmCoopVo.setTreeNames(jsSysOffice.getTreeNames());
                statisticFmCoopVo.setQuantity(count);
                redisFlag = redisUtils.hSet(key, itemKey, JSON.toJSONString(statisticFmCoopVo));
                if (!redisFlag) {
                    throw new FarmException(CommonConstant.EX_DB_REDIS_ERROR, "系统缓存数据库异常");
                }
            }
        }
        return ResultUtil.success();
    }

    /**
     * ----------------------------- 分割线 以下是setter方法，用于替换field上的@Autowired -----------------------------
     **/

    @Autowired
    public void setMapper(FmCoopMapper mapper) {
        this.mapper = mapper;
    }

    @Autowired
    @Lazy
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Autowired
    @Lazy
    public void setJsSysOfficeService(IJsSysOfficeService jsSysOfficeService) {
        this.jsSysOfficeService = jsSysOfficeService;
    }

}
